package com.meitianhui.convenitenbuy.module.home.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.module.home.adapter.NearByStoreAdapter;
import com.meitianhui.convenitenbuy.module.home.contract.NearByStoreContract;
import com.meitianhui.convenitenbuy.module.home.di.DaggerHomeComponent;
import com.meitianhui.convenitenbuy.module.home.di.HomeModule;
import com.meitianhui.convenitenbuy.module.home.presenter.NearByStorePresenter;
import com.meitianhui.convenitenbuy.module.mine.model.rxbusBean.CollectStoreEventBean;
import com.meitianhui.convenitenbuy.module.order.model.bean.EmptyInfo;
import com.meitianhui.convenitenbuy.module.store.model.StoreInfo;
import com.meitianhui.convenitenbuy.module.store.ui.activity.StoreMapActivity;
import com.meitianhui.convenitenbuy.util.LocationService;
import com.meitianhui.convenitenbuy.util.PreferenceUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.SettingStoreDialog;

import java.util.List;

import javax.inject.Inject;

/**
 * Created by Administrator on 2017/11/28.
 */

public class NearByStoreActivity extends BaseToolbarActivity implements NearByStoreContract.View {

    private RecyclerView mRvNearBy;
    private TextView mTvLocation;
    private int mPageIndex = 1;
    private int mPageSize = 20;
    private LocationClient mLocationClient;
    private LocationService locationService;
    private String mGoodsCode;//商品码
    private String mGoodsUrl;//淘口令
    private String mTaoBaoLink;//淘宝链接
    private LatLng mLatLng;
    private NearByStoreAdapter mAdapter;
    private View mNotDataView;
    private List<StoreInfo.Convenient> convenientList;
    private SettingStoreDialog mSettingStoreDialog;
    @Inject
    NearByStorePresenter presenter;

    @Override
    protected int setView() {
        return R.layout.activity_near_by_store;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerHomeComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .homeModule(new HomeModule(this))
                .build()
                .inject(this);
        setTbTitle("每天惠");
        setTbMenu(R.mipmap.icon_store_radar);
        mRvNearBy = getViewById(R.id.rv_near_by);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRvNearBy.setLayoutManager(layoutManager);
        mNotDataView = getLayoutInflater().inflate(R.layout.data_empty_goods,
                (ViewGroup) mRvNearBy.getParent(), false);
        mTvLocation = getViewById(R.id.tv_location);
        initIntent();
        initData();
    }


    private void initIntent() {
        Intent intent = this.getIntent();
        mGoodsCode = intent.getStringExtra("goods_code");   //商品码
        mGoodsUrl = intent.getStringExtra("goods_url");     //淘口令
        mTaoBaoLink = intent.getStringExtra("taobao_link"); //商品价格
        locationService = new LocationService(this);
        locationService.registerListener(mListener);
    }

    private void initData() {
        locationService.start();
        mAdapter = new NearByStoreAdapter(null);
        mRvNearBy.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mSettingStoreDialog = new SettingStoreDialog(NearByStoreActivity.this,
                        R.style.dialog_with_alpha, new SettingStoreDialog.AlertDialogListener() {
                    @Override
                    public void onConfirmClick() {
                        mSettingStoreDialog.dismiss();
                        presenter.officialStorePost(
                                convenientList.get(position).getStores_id(),
                                convenientList.get(position).getStores_name(),
                                mGoodsCode, mGoodsUrl);
                        presenter.settingDefaultStore(convenientList.get(position).getStores_id());
                    }

                    @Override
                    public void onCancelClick() {
                        mSettingStoreDialog.dismiss();
                        presenter.officialStorePost(
                                convenientList.get(position).getStores_id(),
                                convenientList.get(position).getStores_name(),
                                mGoodsCode, mGoodsUrl);
                    }
                });
                mSettingStoreDialog.show();
                mSettingStoreDialog.showCancelBtn(true);
                mSettingStoreDialog.setDialogTitle("提示");
                mSettingStoreDialog.setDialogContent("是否将此门店设为默认门店");
            }
        });
    }

    @Override
    protected void clickMenu() {
        super.clickMenu();
        startActivity(new Intent(NearByStoreActivity.this, StoreMapActivity.class));
    }

    @Override
    protected void onRefreshData() {
        locationService.start();
    }

    @Override
    public void getStoreListSuccess(StoreInfo data) {
        refreshFinish();
        final int size = data.getList() == null ? 0 : data.getList().size();
        mAdapter.setNewData(data.getList());
        if (size == 0) {
            mAdapter.setEmptyView(mNotDataView);
        }
        convenientList = mAdapter.getData();
    }

    @Override
    public void officialStorePostSuccess(EmptyInfo data) {
        mSettingStoreDialog.dismiss();
        TipUtils.showToast(App.getInstance(), "领取成功", 1);
        if (!TextUtils.isEmpty(mTaoBaoLink)) {
            SystemUtils.open(NearByStoreActivity.this, mTaoBaoLink, data.order_id);
        } else {
            Intent intent = new Intent(NearByStoreActivity.this, HomeOrderActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void officialStorePostFail(int code, String msg) {
    }

    @Override
    public void settingDefaultStoreSuccess() {
        RxBus.get().post(new CollectStoreEventBean(Constants.COLLECT_MENU_COMFIRM));
        TipUtils.showToast(App.getInstance(), "设置成功!", 2);
    }

    @Override
    public void showError(String msg) {
    }

    private BDLocationListener mListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                locationService.stop();
                if (location.getAddrStr() != null && !location.getAddrStr().isEmpty() && location.getAddrStr().contains("省")) {
                    mTvLocation.setText(location.getAddrStr().substring(location.getAddrStr().indexOf("省") + 1, location.getAddrStr().length()));
                }
                //保存经纬度
                PreferenceUtils.putString(NearByStoreActivity.this, Constants.LONGITUDE, location.getLongitude() + "");
                PreferenceUtils.putString(NearByStoreActivity.this, Constants.LATITUDE, location.getLatitude() + "");
                PreferenceUtils.putString(NearByStoreActivity.this, Constants.CITY, location.getCity() + "");
                PreferenceUtils.putString(NearByStoreActivity.this, Constants.DISTRICT, location.getDistrict() + "");
                mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
                presenter.getStoreList(location.getLongitude() + "", location.getLatitude() + "", mPageIndex + "", mPageSize + "");
            } else {
                TipUtils.showToast(App.getInstance(), "获取位置失败!", 2);
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.stop();
            mLocationClient = null;
        }
        if (locationService != null) {
            locationService.unregisterListener(mListener);
        }
    }

}
